package com.example.mall.service.impl;

import com.example.mall.mapper.SpManageMapper;
import com.example.mall.mapper.SpPermissionApiMapper;
import com.example.mall.mapper.SpPermissionMapper;
import com.example.mall.mapper.SpRoleMapper;
import com.example.mall.pojo.*;
import com.example.mall.service.RightService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@AllArgsConstructor
public class RightServiceImpl implements RightService {

    SpManageMapper manageMapper;
    SpRoleMapper roleMapper;
    SpPermissionMapper permissionMapper;
    SpPermissionApiMapper permissionApiMapper;

    @Override
    public List<Menu> getMenuByUserId(int userId) {
       SpManager manager= manageMapper.selectById(userId);
       if(manager==null){
           return null;
       }
        Integer roleId = manager.getRole_id();
        SpRole role= roleMapper.selectById(roleId.shortValue());
        if(role==null){
            return null;
        }
        String[] strIds = role.getPs_ids().split(",");
        // 将 字符串的数组 转换 为 Short的列表
        ArrayList<Short> ids = new ArrayList<>();
        for(String str : strIds) {
            ids.add(Short.parseShort(str));
        }
        System.out.println(ids);
//                3. 根据 菜单 ID 列表 得到 用户的 一级菜单
        List<Menu> menuList = getMenusByParentId(ids, 0);
        for(Menu menu1: menuList) {
            // 根据 父菜单的 ID 去 找 子菜单
            List<Menu> menuList2 = getMenusByParentId(ids, menu1.getId().intValue());
            //  将子菜单的列表 赋值给 children
            menu1.setChildren(menuList2);
        }
        return menuList;
    }

    @Override
    public List<NewSpPermission> getList() {
        List<NewSpPermission> spPermissions = permissionMapper.selectList();

        return spPermissions;
    }

    private List<Menu> getMenusByParentId(ArrayList<Short> ids, Integer parentId) {
//                3. 根据 菜单 ID 列表 得到 用户的 一级菜单

        List<SpPermission> permList = permissionMapper.selectByPId(parentId.shortValue());
        ArrayList<Menu> menus = new ArrayList<>();
        for(SpPermission perm: permList) {
            System.out.println(perm);
           SpPermissionApi permissionApi= permissionApiMapper.selectById(perm.getPs_id());
            System.out.println("============" + perm.getPs_id());
            if(permissionApi==null){
               Menu menu = new Menu(perm.getPs_id(), perm.getPs_name(), "", null);
               menus.add(menu);
                System.out.println("menu"+menu);
            }
            Menu menu = new Menu(perm.getPs_id(), perm.getPs_name(), permissionApi.getPs_api_path(), null);
            menus.add(menu);
        }
        return menus;
    }
}

